package utilities.print.menu;

import utilities.print.log.LogMessage;

import java.util.*;

/**
 * 选项菜单类 用于显示功能项 和 传递调用功能项
 */
public class Menu {
    private final TreeMap<String,MenuExecute> menu;
    private final List<String> menuNames;
    private final String name;
    private final LogMessage log;

    public Menu(TreeMap<String, MenuExecute> menu,String menuName) {
        this.name = menuName;
        this.menu = menu;
        menuNames = menu.keySet().stream().toList();
        log = new LogMessage(menuName,false);
    }

    /**
     * 启动菜单交互
     */
    public void runMenu() throws Exception {
        while(printMenu() == 0){
            log.print("");
            emptyPrint();
        }
        emptyPrint();
    }

    /**
     * 打印菜单并等待,用户选择不在菜单中已有的选择，退出
     * @return 非零值表示用户退出菜单
     * @throws Exception 使用菜单功能时发生的错误
     */
    public int printMenu() throws Exception{
        line();
        System.out.println(name + " ,输入没有的数字选项离开");
        line();

        int oper = 0;
        for(String s : menu.keySet()){
            System.out.println(oper++ + "-" + s);
        }

        line();
        System.out.print("选项: ");
        Scanner in  = new  Scanner(System.in);
        int num = in.nextInt();
        line();

        if (num >= 0 && num < menuNames.size()){
            emptyPrint();
            menu.get(menuNames.get(num)).execute();
            return 0;
        }
        return num;
    }

    /**
     * 打印一个宽为35的分隔线
     */
    public static void line(){
        System.out.println("_".repeat(35));
    }

    /**
     * 清空输出屏幕
     */
    public static void emptyPrint(){
        System.out.print("\r\b".repeat(4096));
        System.out.print(" ".repeat(4096));
        System.out.print("\b".repeat(4096));

        System.out.println("\n".repeat(20));
    }
}
